import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap } from '@/config/router.config'

// hack router push callback
const originalPush = Router.prototype.push
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}


Vue.use(Router)

const createRouter = () =>
  new Router({
    mode: 'history',
    routes: constantRouterMap,
    scrollBehavior(to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition;
      } else {
        return { x: 0, y: 0 };
      }
    },
  });

const router = createRouter();

export const resetRouter = () => {
  const newRouter = createRouter();
  Router.matcher = newRouter.matcher;
}

/* 路由异常错误处理，尝试解析一个异步组件时发生错误，重新渲染目标页面 */
router.onError(error => {
  const pattern = /Loading chunk (\w)+ failed/g;
  const isError = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isError) {
    router.replace(targetPath).then();
  }
});

export default router;
